package com.tencent.qcloud.timchat.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.bxd.baodan.R;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.item.ChatQABean;
import com.bxd.baodan.item.PlanerBean;
import com.bxd.baodan.util.GsonUtil;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.LogUtil;
import com.bxd.baodan.util.LoginIMUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.util.SpKey;
import com.bxd.baodan.util.SpUtil;
import com.bxd.baodan.util.StringUtil;
import com.tencent.TIMConversationType;
import com.tencent.TIMCustomElem;
import com.tencent.TIMManager;
import com.tencent.TIMMessage;
import com.tencent.TIMMessageDraft;
import com.tencent.TIMMessageStatus;
import com.tencent.qcloud.presentation.presenter.ChatPresenter;
import com.tencent.qcloud.presentation.viewfeatures.ChatView;
import com.tencent.qcloud.timchat.adapters.ChatAdapter;
import com.tencent.qcloud.timchat.model.AutoQAMessage;
import com.tencent.qcloud.timchat.model.CustomMessage;
import com.tencent.qcloud.timchat.model.FileMessage;
import com.tencent.qcloud.timchat.model.HeadCardMessage;
import com.tencent.qcloud.timchat.model.ImageMessage;
import com.tencent.qcloud.timchat.model.LeftListMessage;
import com.tencent.qcloud.timchat.model.LeftTextMessage;
import com.tencent.qcloud.timchat.model.Message;
import com.tencent.qcloud.timchat.model.MessageFactory;
import com.tencent.qcloud.timchat.model.TextMessage;
import com.tencent.qcloud.timchat.model.VoiceMessage;
import com.tencent.qcloud.timchat.utils.FileUtil;
import com.tencent.qcloud.timchat.utils.MediaUtil;
import com.tencent.qcloud.timchat.utils.RecorderUtil;
import com.tencent.qcloud.ui.ChatInput;
import com.tencent.qcloud.ui.TemplateTitle;
import com.tencent.qcloud.ui.VoiceSendingView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * fixme 解决闪屏问题,闪屏是因为activity动画,内在的原因是普通activity向普通Activity跳转时才会产生.而不用BaseActivity
 * fixme 的原因是软键盘的弹出会使titleBar也整体上弹
 */
public class ChatActivity extends Activity implements ChatView, LeftListMessage.SendListener {


    private List<Message> messageList = new ArrayList<>();
    public ChatAdapter adapter;
    private ListView listView;
    private ChatPresenter presenter;
    private ChatInput input;
    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
    private static final int IMAGE_STORE = 200;
    private static final int FILE_CODE = 300;
    private static final int IMAGE_PREVIEW = 400;
    private Uri fileUri;
    private VoiceSendingView voiceSendingView;
    private String identify;
    private RecorderUtil recorder = new RecorderUtil();
    private TIMConversationType type;
    boolean isFistEnter;
    private String planerName = "";


    public static void navToChat(Context context, String identify, TIMConversationType type) {
        Intent intent = new Intent(context, ChatActivity.class);
        intent.putExtra("identify", identify);
        intent.putExtra("type", type);
        context.startActivity(intent);

    }

    public static void navToChat(Context context, String identify, boolean isPlaner, PlanerBean.PlanerBean_ bean_, TIMConversationType type) {
        Intent intent = new Intent(context, ChatActivity.class);
        intent.putExtra("identify", identify);
        intent.putExtra("type", type);
        intent.putExtra("isPlaner", isPlaner);
        intent.putExtra("planer_bean", bean_);
        context.startActivity(intent);

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        setContentView(R.layout.activity_chat);

        loadAutoQAData();

        //发送照片信息时,Activity可能会被销毁后重新创建,但这时im已经退出且没有初始化,导致发送文字崩溃bug
        //解决:检测到未初始化时重新登录
        if (TIMManager.getInstance().getSdkAppId() == 0) {
            //未初始化
            LoginIMUtil loginUtil = new LoginIMUtil(this);
            loginUtil.initIM();
            loginUtil.loginIM();
        }
        isFistEnter = true;
        identify = getIntent().getStringExtra("identify");
        type = (TIMConversationType) getIntent().getSerializableExtra("type");

        presenter = new ChatPresenter(this, identify, type);
        input = (ChatInput) findViewById(R.id.input_panel);
        input.setChatView(this);
        adapter = new ChatAdapter(this, R.layout.item_message, messageList);
        adapter.setAgentId(identify);
        listView = (ListView) findViewById(R.id.list);
        listView.setAdapter(adapter);
        listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
        listView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        input.setInputMode(ChatInput.InputMode.NONE);
                        break;
                }
                return false;
            }
        });
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {

            private int firstItem;

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && firstItem == 0) {
                    //如果拉到顶端读取更多消息
                    presenter.getMessage(messageList.size() > 0 ? messageList.get(0).getMessage() : null);

                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                firstItem = firstVisibleItem;
            }
        });
        registerForContextMenu(listView);
        final TemplateTitle title = (TemplateTitle) findViewById(R.id.chat_title);
        switch (type) {
            case C2C:
                title.setMoreImg(R.drawable.btn_person);
                if (getIntent().getBooleanExtra("isPlaner", false)) {

                    PlanerBean.PlanerBean_ bean_ = (PlanerBean.PlanerBean_) getIntent().getSerializableExtra("planer_bean");

                    String faceUrl = bean_.avatar;

                    planerName = bean_.nickname;

                    title.setTitleText("与" + planerName + "沟通中");

                    if (adapter != null && faceUrl != null && !"".equals(faceUrl)) {
                        adapter.setToShowUrl(faceUrl);
                        adapter.notifyDataSetChanged();
                    }


                    if (isFistEnter) {

                        HeadCardMessage headCardMessage = new HeadCardMessage(bean_);
                        messageList.add(headCardMessage);

                        String cache = SpUtil.getInstance().getString(SpKey.CHAT_AUTO_QA);
                        if (!StringUtil.isEmpty(cache)) {
                            addFistEnterItem(cache);
                        } else {
                            NetUtil netUtil = new NetUtil(this, JsonApi.QUESTION_AIQA);
                            netUtil.postRequest("", new NetUtil.DataListener() {
                                @Override
                                public void onComplete(String data) {
                                    SpUtil.getInstance().savaString(SpKey.CHAT_AUTO_QA, data);
                                    addFistEnterItem(data);
                                }
                            });
                        }

                    }


                } else {

                    // FIXME: 17/9/15 这里需要修改成从上层获取用户信息,有空改
                    NetUtil net = new NetUtil(ChatActivity.this, JsonApi.GET_USER_INFO_FOR_CHAT);

                    net.setParams("uids", identify);
                    net.postRequest("", new NetUtil.RequestStringListener() {
                        @Override
                        public void onComplete(String result) {

                            try {
                                JsonObject jsonObject = new Gson().fromJson(JSONUtil.getData(result), JsonObject.class);

                                JsonObject user = jsonObject.getAsJsonObject(identify);
                                if (user != null) {
                                    if (adapter != null) {
                                        adapter.setAgentId(user.get("u_id").getAsString());
                                    }
                                    planerName = user.get("u_realname").getAsString();


                                    title.setTitleText("与" + user.get("u_realname").getAsString() + "沟通中");
                                    String faceUrl = user.get("u_avatar").getAsString();
                                    if (adapter != null && faceUrl != null && !"".equals(faceUrl)) {
                                        adapter.setToShowUrl(faceUrl);
                                        adapter.notifyDataSetChanged();
                                    }

                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            adapter.notifyDataSetChanged();
                        }
                    });

                }


                break;


        }
        voiceSendingView = (VoiceSendingView) findViewById(R.id.voice_sending);
        presenter.start();
    }

    private void addFistEnterItem(String cache) {
        ChatQABean chatQABean = GsonUtil.fromJson(cache, ChatQABean.class);
        LeftListMessage message = new LeftListMessage(chatQABean, this);
        messageList.add(message);
        isFistEnter = !isFistEnter;
    }

    private void loadAutoQAData() {
        NetUtil netUtil = new NetUtil(this, JsonApi.QUESTION_AIQA);
        netUtil.postRequest("", new NetUtil.DataListener() {
            @Override
            public void onComplete(String data) {
                SpUtil.getInstance().savaString(SpKey.CHAT_AUTO_QA, data);
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        //退出聊天界面时输入框有内容，保存草稿
        if (input.getText().length() > 0) {
            TextMessage message = new TextMessage(input.getText());
            presenter.saveDraft(message.getMessage());
        } else {
            presenter.saveDraft(null);
        }
        //        RefreshEvent.getInstance().onRefresh();
        presenter.readMessages();
        MediaUtil.getInstance().stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.stop();
    }


    /**
     * 显示消息
     *
     * @param message
     */
    @Override
    public void showMessage(TIMMessage message) {
        if (message == null) {
            adapter.notifyDataSetChanged();
        } else {
            Message mMessage = MessageFactory.getMessage(message);
            if (mMessage != null) {
                if (messageList.size() == 0) {
                    mMessage.setHasTime(null);
                } else {
                    mMessage.setHasTime(messageList.get(messageList.size() - 1).getMessage());
                }
                if (!mMessage.isSelf()) {


                }

                messageList.add(mMessage);
                adapter.notifyDataSetChanged();
                listView.setSelection(adapter.getCount() - 1);
            }
        }

    }

    /**
     * 显示消息
     *
     * @param messages
     */
    @Override
    public void showMessage(List<TIMMessage> messages) {
        int newMsgNum = 0;
        for (int i = 0; i < messages.size(); ++i) {
            Message mMessage = MessageFactory.getMessage(messages.get(i));
            if (mMessage == null || messages.get(i).status() == TIMMessageStatus.HasDeleted)
                continue;
            ++newMsgNum;
            if (i != messages.size() - 1) {
                mMessage.setHasTime(messages.get(i + 1));

                if (mMessage instanceof AutoQAMessage) {
                    ChatQABean.QABean bean = ((AutoQAMessage) mMessage).bean;

                    if (!StringUtil.isEmpty(bean.answer)) {
                        LeftTextMessage leftTextMessage = new LeftTextMessage(bean.answer);
                        messageList.add(0, leftTextMessage);
                        newMsgNum++;

                    } else {
                        ChatQABean bean1 = new ChatQABean();
                        bean1.question = bean.question;

                        LeftListMessage leftListMessage = new LeftListMessage(bean1, this);
                        messageList.add(0, leftListMessage);
                        newMsgNum++;
                    }

                }


                messageList.add(0, mMessage);
            } else {
                mMessage.setHasTime(null);

                //判断是否是自定义消息
                if (mMessage instanceof AutoQAMessage) {
                    ChatQABean.QABean bean = ((AutoQAMessage) mMessage).bean;

                    if (!StringUtil.isEmpty(bean.answer)) {
                        LeftTextMessage leftTextMessage = new LeftTextMessage(bean.answer);
                        messageList.add(0, leftTextMessage);
                        newMsgNum++;

                    } else {
                        ChatQABean bean1 = new ChatQABean();
                        bean1.question = bean.question;

                        LeftListMessage leftListMessage = new LeftListMessage(bean1, this);
                        messageList.add(0, leftListMessage);
                        newMsgNum++;
                    }

                }
                messageList.add(0, mMessage);
            }
        }

        adapter.notifyDataSetChanged();
        listView.setSelection(newMsgNum);

    }

    /**
     * 清除所有消息，等待刷新
     */
    @Override
    public void clearAllMessage() {
        messageList.clear();
    }

    /**
     * 发送消息成功
     *
     * @param message 返回的消息
     */
    @Override
    public void onSendMessageSuccess(TIMMessage message) {
        showMessage(message);
    }

    /**
     * 发送消息失败
     *
     * @param code 返回码
     * @param desc 返回描述
     */
    @Override
    public void onSendMessageFail(int code, String desc, TIMMessage message) {
        long id = message.getMsgUniqueId();
        for (Message msg : messageList) {
// FIXME: 18/1/29 修复空消息的问题,可能是因为headMsg的问题
            if (msg.getMessage() != null && msg.getMessage().getMsgUniqueId() == id) {
                switch (code) {
                    case 80001:
                        //发送内容包含敏感词
                        msg.setDesc(getString(R.string.chat_content_bad));
                        adapter.notifyDataSetChanged();
                        break;
                }
            }
        }

    }

    /**
     * 发送图片消息
     */
    @Override
    public void sendImage() {
        LogUtil.e("图片: ");
        Intent intent_album = new Intent("android.intent.action.GET_CONTENT");
        intent_album.setType("image/*");
        startActivityForResult(intent_album, IMAGE_STORE);
    }

    /**
     * 发送照片消息
     */
    @Override
    public void sendPhoto() {
        Intent intent_photo = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent_photo.resolveActivity(getPackageManager()) != null) {
            File tempFile = FileUtil.getTempFile(FileUtil.FileType.IMG);
            if (tempFile != null) {
                fileUri = Uri.fromFile(tempFile);
            }
            intent_photo.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
            startActivityForResult(intent_photo, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
        }
    }

    /**
     * 发送文本消息
     */
    @Override
    public void sendText() {
        Message message = new TextMessage(input.getText());
        presenter.sendMessage(message.getMessage());
        input.setText("");
    }

    /**
     * 发送文件
     */
    @Override
    public void sendFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        startActivityForResult(intent, FILE_CODE);
    }


    /**
     * 开始发送语音消息
     */
    @Override
    public void startSendVoice() {
        voiceSendingView.setVisibility(View.VISIBLE);
        voiceSendingView.showRecording();
        recorder.startRecording();

    }

    /**
     * 结束发送语音消息
     */
    @Override
    public void endSendVoice() {
        voiceSendingView.release();
        voiceSendingView.setVisibility(View.GONE);
        recorder.stopRecording();
        if (recorder.getTimeInterval() < 1) {
            Toast.makeText(this, getResources().getString(R.string.chat_audio_too_short), Toast.LENGTH_SHORT).show();
        } else {
            Message message = new VoiceMessage(recorder.getTimeInterval(), recorder.getFilePath());
            presenter.sendMessage(message.getMessage());
        }
    }

    /**
     * 发送小视频消息
     *
     * @param fileName 文件名
     */
    @Override
    public void sendVideo(String fileName) {
    }


    /**
     * 结束发送语音消息
     */
    @Override
    public void cancelSendVoice() {

    }

    /**
     * 正在发送
     */
    @Override
    public void sending() {
//        if (type == TIMConversationType.C2C) {
//            Message message = new CustomMessage(CustomMessage.Type.TYPING);
//            presenter.sendOnlineMessage(message.getMessage());
//        }
    }

    /**
     * 显示草稿
     */
    @Override
    public void showDraft(TIMMessageDraft draft) {
        input.getText().append(TextMessage.getString(draft.getElems(), this));
    }


    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        Message message = messageList.get(info.position);
        menu.add(0, 1, Menu.NONE, getString(R.string.chat_del));
        if (message.isSendFail()) {
            menu.add(0, 2, Menu.NONE, getString(R.string.chat_resend));
        }
        if (message instanceof ImageMessage || message instanceof FileMessage) {
            menu.add(0, 3, Menu.NONE, getString(R.string.chat_save));
        }
    }


    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        Message message = messageList.get(info.position);
        switch (item.getItemId()) {
            case 1:
                message.remove();
                messageList.remove(info.position);
                adapter.notifyDataSetChanged();
                break;
            case 2:
                messageList.remove(message);
                presenter.sendMessage(message.getMessage());
                break;
            case 3:
                message.save();
                break;
            default:
                break;
        }
        return super.onContextItemSelected(item);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
            if (resultCode == RESULT_OK && fileUri != null) {
                showImagePreview(fileUri.getPath());
            }
        } else if (requestCode == IMAGE_STORE) {
            if (resultCode == RESULT_OK && data != null) {
                showImagePreview(FileUtil.getFilePath(this, data.getData()));
            }

        } else if (requestCode == FILE_CODE) {
            if (resultCode == RESULT_OK) {
                sendFile(FileUtil.getFilePath(this, data.getData()));
            }
        } else if (requestCode == IMAGE_PREVIEW) {
            if (resultCode == RESULT_OK) {
                boolean isOri = data.getBooleanExtra("isOri", false);
                String path = data.getStringExtra("path");
                File file = new File(path);
                if (file.exists() && file.length() > 0) {
                    if (file.length() > 1024 * 1024 * 10) {
                        Message message = new ImageMessage(path, false);
                        presenter.sendMessage(message.getMessage());
                    } else {
                        Message message = new ImageMessage(path, isOri);
                        presenter.sendMessage(message.getMessage());
                    }
                } else {
                    Toast.makeText(this, getString(R.string.chat_file_not_exist), Toast.LENGTH_SHORT).show();
                }
            }
        }

    }


    private void showImagePreview(String path) {
        if (path == null)
            return;
        Intent intent = new Intent(this, ImagePreviewActivity.class);
        intent.putExtra("path", path);
        startActivityForResult(intent, IMAGE_PREVIEW);
    }

    private void sendFile(String path) {
        if (path == null)
            return;
        File file = new File(path);
        if (file.exists()) {
            if (file.length() > 1024 * 1024 * 10) {
                Toast.makeText(this, getString(R.string.chat_file_too_large), Toast.LENGTH_SHORT).show();
            } else {
                Message message = new FileMessage(path);
                presenter.sendMessage(message.getMessage());
            }
        } else {
            Toast.makeText(this, getString(R.string.chat_file_not_exist), Toast.LENGTH_SHORT).show();
        }

    }


    /**
     * 发送自定义消息,评分
     */
    public void sendCustomMessage(String hipi) {
        TIMMessage timMassage = new TIMMessage();
        TIMCustomElem timCustomElem = new TIMCustomElem();
        timCustomElem.setData(hipi.getBytes());
        timMassage.addElement(timCustomElem);
        CustomMessage message = new CustomMessage(timMassage);
        presenter.sendMessage(message.getMessage());
    }


    @Override
    public void send(ChatQABean.QABean bean) {
        String jsonStr = GsonUtil.toJson(bean);

        TIMMessage timMassage = new TIMMessage();
        TIMCustomElem timCustomElem = new TIMCustomElem();
        timCustomElem.setData(jsonStr.getBytes());
        timMassage.addElement(timCustomElem);
        AutoQAMessage message = new AutoQAMessage(timMassage);


        presenter.sendMessage(message.getMessage());

        if (!StringUtil.isEmpty(bean.answer)) {
            LeftTextMessage leftTextMessage = new LeftTextMessage(bean.answer);
            messageList.add(leftTextMessage);
        } else {
            ChatQABean bean1 = new ChatQABean();
            bean1.question = bean.question;

            LeftListMessage leftListMessage = new LeftListMessage(bean1, this);
            messageList.add(leftListMessage);
        }
        adapter.notifyDataSetChanged();
        listView.smoothScrollToPosition(adapter.getCount()-1);


    }
}
